using SerialPortCommunicationProject.Tools;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO.Ports;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using Tool;

namespace SerialPortCommunicationProject
{
    /// <summary>
    /// DeviceSelectWindow.xaml 的交互逻辑
    /// </summary>
    public partial class DeviceSelectWindow : Window
    {
        Database database = Database.GetInstance();

        private ObservableCollection<string> lstClientIp;

        private int openedDeviceIndex = -1;//不允许多个设备同时打开通迅的前提下使用

        //private Device device;//当前用户选中设备

        //public Device Device { get; }

        private void SetUsingMode(bool value)
        { 
            if (!value)
            {
                //to normal
                Panel_Normal.Visibility = Visibility.Visible;
                Panel_Normal.IsEnabled = true;
                Panel_DeviceSelect.Visibility = Visibility.Collapsed;
                Panel_DeviceSelect.IsEnabled = false;

                this.Btn_Switch.Visibility = Visibility.Visible;
                this.Btn_Switch.IsEnabled = true;
                this.Panel_StatusBar.Visibility = Visibility.Collapsed;
                this.CheckBox_AutoSend.Visibility = Visibility.Collapsed;

                if (openedDeviceIndex != -1)
                {
                    CloseCommunication();
                    openedDeviceIndex = -1;
                }
                App.CurrentDevice = database.GetNormalDevice();
            }
            else
            {
                // normal to device select
                Panel_Normal.Visibility = Visibility.Collapsed;
                Panel_Normal.IsEnabled = false;
                Panel_DeviceSelect.Visibility = Visibility.Visible;
                Panel_DeviceSelect.IsEnabled = true;

                this.Panel_StatusBar.Visibility = Visibility.Visible;
                this.CheckBox_AutoSend.Visibility = Visibility.Visible;
                this.Btn_Switch.Visibility = Visibility.Collapsed;
                this.Btn_Switch.IsEnabled = false;

                UpdateCurrentDevice();

                database.UpdateNormalDevice(App.CurrentDevice);
                CloseCommunication();

                //初始化窗口这里只显示一个设备及其指令
                App.LstDevices = database.LoadAllDevices();
                if (App.LstDevices != null)
                {
                    foreach (Device d in App.LstDevices)
                    {
                        d.Commands.Add(new Command() { Name = "+" });
                    }
                }
                else
                {
                    App.LstDevices = new ObservableCollection<Device>();
                }
                App.LstDevices.Add(StaticData.DefaultDeviceToAdd);
                

                // 2个ListBox数据绑定
                this.lBox_Devices.ItemsSource = App.LstDevices;
                this.lBox_Devices.DisplayMemberPath = "Name";
                lBox_Devices.SelectedIndex = App.LstDevices.Count - 1;
                this.lBox_Commands.ItemsSource = App.LstDevices[App.LstDevices.Count - 1].Commands;
                this.lBox_Commands.DisplayMemberPath = "Name";
                lBox_Commands.Visibility = Visibility.Collapsed;
                App.CurrentDevice = App.LstDevices[App.LstDevices.Count-1];
            }
            ViewModelHelper.SetEncoding(this);
            usingMode = value;
        }

        private bool usingMode;

        private void UpdateCurrentDevice()
        {
            App.CurrentDevice.PortName = CbBox_SerialPort.Text;
            int.TryParse(CbBox_BaudRate.Text, out int baudRate);
            App.CurrentDevice.BaudRate = baudRate;
            int.TryParse(CbBox_DataBits.Text, out int dataBits);
            App.CurrentDevice.DataBits = dataBits;
            App.CurrentDevice.StopBits = App.StringToStopBits(CbBox_StopBits.Text);
            App.CurrentDevice.Parity = App.StringToParity(CbBox_ParityBits.Text);
            App.CurrentDevice.IsServer = App.StringToIsServer(CbBox_CorS.Text);
            App.CurrentDevice.Ip = CbBox_IpAddress.Text;
            int.TryParse(TBox_Port.Text, out int port);
            App.CurrentDevice.Port = port;
        }
       

        /// <summary>
        /// 加载默认选中的TabItem的内容
        /// 1. 从XML获得Device名称及其指令列表的数据
        /// 2. 加载数据到TabItem中
        /// </summary>
        public DeviceSelectWindow()
        {
            InitializeComponent();
            this.Title += App.GetEdition().ToString();//添加版本号到本窗口标题

            
            //default value
            this.lBox_Devices.SelectedIndex = 0;
            ViewModelHelper.RTBox = this.RichTextBoxDataRecord;//注册害
            ViewModelHelper.TBox = this.Tbox_Send;
            ViewModelHelper.BtnSwitch = this.Btn_Switch;
            ViewModelHelper.CommunicationStatus = this.TbBlock_CommunicationStatus;
            ViewModelHelper.SetEncoding(this);
            MessageBox.Show(database.TestConnection());

            if (!database.CreateDataBaseIfNotExists(StaticData.DATABASENAME))
            {
                return;
            }
            if (!database.CreateTableNamedDevice(StaticData.DATABASENAME, StaticData.DEVICETABLENAME))
            {
                return;
            }
            if (!database.CreateTableNamedCommand(StaticData.DATABASENAME, StaticData.COMMANDTABLENAME))
            {
                return;
            }

        }

        public void AutoSelectDevice()
        {
            //this.lBox_Commands.ItemsSource = App.LstDevices[this.lBox_Devices.SelectedIndex].Commands;
            this.lBox_Commands.Visibility = Visibility.Visible;
            SelectedDevice(this.lBox_Devices);
        }
        
        // set current device and communication
        private void SelectedDevice(ListBox listBox)
        {
            int index = listBox.SelectedIndex;
            App.CurrentDevice = App.LstDevices[index];//更新当前设备
            if (App.CurrentDevice.Name == "+")
            {
                lBox_Commands.Visibility = Visibility.Collapsed;
            }
            else
            {
                // 如果用户点击选择设备
                lBox_Commands.Visibility = Visibility.Visible;//显示指令窗口
                lBox_Commands.ItemsSource = App.CurrentDevice.Commands;
                lBox_Commands.DisplayMemberPath = "Name";
                if (App.Comm == null)
                {
                    if (App.CurrentDevice.CommMode == "串口")
                    {
                        App.Comm = new SerialPortCommunication(App.CurrentDevice.PortName, App.CurrentDevice.BaudRate, App.CurrentDevice.DataBits, App.CurrentDevice.Parity, App.CurrentDevice.StopBits);
                    }
                    else if (App.CurrentDevice.CommMode == "Socket(TCP)")
                    {
                        if (App.CurrentDevice.IsServer)
                        {
                            App.Comm = new SocketTcpServerCommunication(App.CurrentDevice.Ip, App.CurrentDevice.Port);
                        }
                        else
                        {
                            App.Comm = new SocketTcpClientCommunication(App.CurrentDevice.Ip, App.CurrentDevice.Port);
                        }
                    }
                }
                UpdateStatusBarOfCurrentDevice(App.CurrentDevice);
            }
        }
        private void UpdateStatusBarOfCurrentDevice(Device device)
        {
            string value = null;
            if (device.CommMode == "串口" )
            {
                value = $"所选设备名称：{device.Name} | 串口号：{device.PortName} | 波特率：{device.BaudRate} | 数据位：{device.DataBits} | 校验位：{device.Parity} | 停止位：{device.StopBits}";
            }
            else
            {
                //Socket TCP
                string ipString = "远程主机IP";
                string portString = "远程主机端口";
                if (device.IsServer)
                {
                    ipString = "本地主机IP";
                    portString = "本地主机端口";
                }
                value = $"所选设备名称：{device.Name} | {ipString}：{device.Ip} | {portString}：{device.Port}";
            }
            this.Tblock_Selected.Text = value;
        }
        private void LBox_Device_Click(object sender, MouseButtonEventArgs e)
        {
            if (lBox_Devices.SelectedIndex < 0)
            {
                return;
            }

            var listBox = sender as ListBox;

            SelectedDevice(listBox);//更新当前设备

            #region 隐藏状态栏设备相关内容
            Panel_SerialPortName.Visibility = Visibility.Collapsed;
            Panel_SocketTcp.Visibility = Visibility.Collapsed;
            #endregion
            if (App.CurrentDevice.Name == "+")
            {
                App.CurrentDevice.Commands = new ObservableCollection<Command>() { new Command() { Name="+"} };
                NewDeviceWindow newDeviceWindow = new NewDeviceWindow();
                newDeviceWindow.Owner = this;

                newDeviceWindow.ShowDialog();
            }
            else
            {
                App.CurrentDevice.Commands[App.CurrentDevice.Commands.Count - 1].Name = "+";//更改界面显示
                
                lBox_Commands.ItemsSource = App.CurrentDevice.Commands;
                lBox_Commands.DisplayMemberPath = "Name";
                lBox_Commands.SelectedIndex = 0;
            }
        }

        private void SelectedCommand(ListBox listBox)
        {
            int index = listBox.SelectedIndex;
            App.CurrentCommand = App.CurrentDevice.Commands[index];//更新当前指令
            if (App.CurrentCommand.Name == "+")
            {
                NewCommandWindow newCommandWindow = new NewCommandWindow(App.CurrentDevice, App.CurrentDevice.Name);
                newCommandWindow.Owner = this;
                newCommandWindow.ShowDialog();
            }
            else
            {
                this.Tbox_Send.Text = (this.lBox_Commands.SelectedItem as Command).Code;
                if (this.CheckBox_AutoSend.IsChecked == true)
                {
                    Btn_Send_Click(null, null);
                }
            }
        }
        

        private void LBox_Command_Click(object sender, MouseButtonEventArgs e)
        {
            var listBox = sender as ListBox;
            int index = listBox.SelectedIndex;
            if (index < 0)
            {
                return;
            }
            SelectedCommand(listBox);
        }


        private void Btn_Send_Click(object sender, RoutedEventArgs e)
        {
            if (App.Comm == null|| App.Comm.IsOpen==false)
            {
                MessageBox.Show("通讯未打开！\n请先打开通讯！");
                CloseCommunication();
                return;
            }
            byte[] sendBuffer = null;

            if (ViewModelHelper.EncodingHere[1] == "HEX")
            {
                try
                {
                    sendBuffer = InteractiveTool.StringToByte(ViewModelHelper.TBox.Text);
                }catch (FormatException ex)
                {
                    sendBuffer = new byte[] { 0xFF };
                    MessageBox.Show("16进制格式不正确！");
                }
            }
            else
            {
                sendBuffer = ASCIIEncoding.ASCII.GetBytes(App.AnalyseEscapeCh(ViewModelHelper.TBox.Text));
            }
            App.Comm?.Send(sendBuffer);
        }

        private void MenuItem_DeleteDevice_Click(object sender, RoutedEventArgs e)
        {
            int index = this.lBox_Devices.SelectedIndex;
            string nameToDelete;
            if (index != App.LstDevices.Count - 1)
            {
                nameToDelete = App.LstDevices[index].Name;

                // 界面删除设备
                App.LstDevices.RemoveAt(index);//索引相对应 所以直接删
                App.CurrentDevice = null;
                App.CurrentCommand = null;

                // xml中删除设备
                //...
                database.RemoveDevice(nameToDelete);
            }
        }

        /// <summary>
        /// 编辑设备参数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuItem_EditDevice_Click(object sender, RoutedEventArgs e)
        {
            if (App.CurrentDevice.Name != "+")
            {
                NewDeviceWindow w = new NewDeviceWindow();
                w.Owner = this;
                lBox_Commands.Visibility = Visibility.Collapsed;
                w.ShowDialog();
            }
        }

        private void Send_Clear_Click(object sender, RoutedEventArgs e)
        {
            this.Tbox_Send.Text = String.Empty;
        }

        private void Recv_Clear_Click(object sender, RoutedEventArgs e)
        {
            this.RichTextBoxDataRecord.Document.Blocks.Clear();
        }

        private void Tbox_Send_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            string encoding;
            if (this.Panel_DeviceSelect.Visibility == Visibility.Visible)
            {
                encoding = App.LstDevices[this.lBox_Devices.SelectedIndex].Encoding;
            }
            else
            {
                encoding = (this.SendSetting_ASCII.IsChecked == true) ? "ASCII" : "HEX";
            }

            FormatType type = App.StringToFormat(encoding);
            App.FormatCommandCode(this.Tbox_Send.Text, this.Tbox_Send, type);
        }

        /// <summary>
        /// 右键菜单-打开通讯
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuItem_OpenCommunication_Click(object sender, RoutedEventArgs e)
        {
            if (App.Comm.IsOpen)
            {
                return;
            }
            try
            {
                OpenCommunication();
                TbBlock_DeviceName.Text = App.CurrentDevice.Name;
            }
            catch (Exception ex)
            {
                MessageBox.Show("通信打开失败，请检查参数设置!");
            }
        }

        /// <summary>
        /// 右键菜单-关闭通讯
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuItem_CloseCommunication_Click(object sender, RoutedEventArgs e)
        {
            CloseCommunication();
        }

        private void MenuItem_EditCommand_Click(object sender, RoutedEventArgs e)
        {
            if (App.CurrentCommand.Name == "+") 
            {
                return;
            }

            NewCommandWindow w = new NewCommandWindow(App.CurrentDevice, App.CurrentDevice.Name);
            w.Owner = this;
            w.ShowDialog();
        }

        private void MenuItem_DeleteCommand_Click(object sender, RoutedEventArgs e)
        {
            int index = this.lBox_Commands.SelectedIndex;
            if (index == App.CurrentDevice.Commands.Count-1)
            {
                return;
            }
            
            Command command = App.CurrentDevice.Commands[index];//当前选中指令
            //command.DeviceName = App.CurrentDevice.Name;
            Command commToRemove = App.CurrentDevice.Commands[index];
            App.CurrentDevice.Commands.RemoveAt(index);

            database.RemoveCommand(App.CurrentDevice.Name, commToRemove.Name);
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            App.ClickItem(this.lBox_Devices,
                this,
                null,
                new Action(() =>
                {
                    this.lBox_Commands.Visibility = Visibility.Hidden;//隐藏指令窗口
                    #region 隐藏状态栏设备相关内容
                    Panel_SerialPortName.Visibility = Visibility.Collapsed;
                    Panel_SocketTcp.Visibility = Visibility.Collapsed;
                    #endregion
                }),
                new Action(() => {
                    SelectedDevice(lBox_Devices);
                }));
        }

        private void Menu_ChangeUI_Click(object sender, RoutedEventArgs e)
        {
            if (this.Panel_Normal.Visibility==Visibility.Visible)
            {
                // 从普通模式切换到设备选择模式
                SetUsingMode(true);
            }
            else
            {
                // 从设备选择模式切换到普通模式
                SetUsingMode(false);
            }
        }

       
        // 通用模式面板加载静态数据
        private Modbus modbus = new Modbus();
        private void Panel_Normal_Loaded(object sender, RoutedEventArgs e)
        {
            // 加载页面中Modbus面板的静态数据
           
            //Data Binding
            this.CbBox_FunctionCode.ItemsSource = StaticData.FunctionCodes;
            this.TBox_Address.SetBinding(TextBox.TextProperty, new Binding("Address") { Source = modbus });
            this.TBox_Start.SetBinding(TextBox.TextProperty, new Binding("Start") { Source = modbus });
            this.TBox_Count.SetBinding(TextBox.TextProperty, new Binding("Count") { Source = modbus });

            //default setting
            this.CbBox_FunctionCode.SelectedIndex = 0;

            // 加载串口和网络通信面板的静态数据
            //Data Binding
            this.CbBox_BaudRate.ItemsSource = StaticData.BaudRates;
            this.CbBox_DataBits.ItemsSource = StaticData.DataBits;
            this.CbBox_ParityBits.ItemsSource = StaticData.ParityBitsList;
            this.CbBox_StopBits.ItemsSource = StaticData.StopBitsList;

            this.CbBox_CorS.ItemsSource = StaticData.COrS;
            this.CbBox_IpAddress.ItemsSource = StaticData.IpList;

            //default setting
            this.CbBox_BaudRate.SelectedIndex = 0;
            this.CbBox_DataBits.SelectedIndex = 0;
            this.CbBox_ParityBits.SelectedIndex = 0;
            this.CbBox_StopBits.SelectedIndex = 0;

            this.CbBox_CorS.SelectedIndex = 0;
            this.CbBox_IpAddress.SelectedIndex = 0;

            App.CurrentDevice = database.GetNormalDevice();
            if (App.CurrentDevice == null)
            {
                App.CurrentDevice = new Device() { Name = "normaldevice", CommMode = StaticData.SERIALPORT, PortName="", BaudRate = 9600, DataBits = 8, Parity = Parity.None, StopBits = StopBits.One, Encoding = StaticData.ASCII,Commands=new ObservableCollection<Command>() };
                database.AddDevice(App.CurrentDevice);
            }

            // 绑定普通设备信息
            CbBox_SerialPort.SetBinding(ComboBox.TextProperty, new Binding("PortName") { Source = App.CurrentDevice });
            CbBox_BaudRate.SetBinding(ComboBox.TextProperty, new Binding("BaudRate") { Source = App.CurrentDevice });
            CbBox_ParityBits.SetBinding(ComboBox.TextProperty, new Binding("Parity") { Source = App.CurrentDevice, Converter=new ParityConverter() });
            CbBox_DataBits.SetBinding(ComboBox.TextProperty, new Binding("DataBits") { Source = App.CurrentDevice });
            CbBox_StopBits.SetBinding(ComboBox.TextProperty, new Binding("StopBits") { Source = App.CurrentDevice, Converter=new StopBitsConverter() });
            CbBox_IpAddress.SetBinding(ComboBox.TextProperty, new Binding("Ip") { Source = App.CurrentDevice });
            TBox_Port.SetBinding(TextBox.TextProperty, new Binding("Port") { Source = App.CurrentDevice, Mode=BindingMode.OneWayToSource});
            CbBox_CorS.SetBinding(ComboBox.TextProperty, new Binding("IsServer") { Source = App.CurrentDevice, Converter = new IsServerConverter() });
            

            
        }

        private void Bt_GenerateCommand_Click(object sender, RoutedEventArgs e)
        {
            List<byte> code = modbus.GenerateCode(this.TBox_Address.Text.Replace(" ", "").PadLeft(2, '0'),
                this.CbBox_FunctionCode.Text.Substring(0, 2),
                this.TBox_Start.Text.Replace(" ", "").PadLeft(4, '0'),
                this.TBox_Count.Text.Replace(" ", "").PadLeft(4, '0'));
            this.Tbox_Send.Text = BitConverter.ToString(code.ToArray()).Replace("-", " ");
        }

        private void CbBox_SerialPort_DropDownOpened(object sender, EventArgs e)
        {
            this.CbBox_SerialPort.ItemsSource = SerialPort.GetPortNames();
        }

        private void CbBox_CorS_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ComboBox comboBox = sender as ComboBox;
            if (comboBox.SelectedIndex == 0)//Client
            {
                this.TBlock_IP.Text = "远程主机地址";
                this.TBlock_Port.Text = "远程主机端口";
                this.CbBox_IpAddress.IsEditable = true;
            }
            else if (comboBox.SelectedIndex == 1)//Server
            {
                this.TBlock_IP.Text = "本地主机地址";
                this.TBlock_Port.Text = "本地主机端口";
                this.CbBox_IpAddress.IsEditable = false;
                this.CbBox_IpAddress.ItemsSource = App.GetServerIpAddresses();
                this.CbBox_IpAddress.SelectedIndex = 0;
            }
        }

        private void OpenCommunication()
        {
            ViewModelHelper.SetEncoding(this);
            if (App.CurrentDevice.CommMode==StaticData.SERIALPORT)
            {
                //serial Port
                App.Comm = new SerialPortCommunication(App.CurrentDevice.PortName, App.CurrentDevice.BaudRate, App.CurrentDevice.DataBits, App.CurrentDevice.Parity, App.CurrentDevice.StopBits);
            }
            else if(App.CurrentDevice.CommMode==StaticData.SOCKETTCP)
            {
                if (App.CurrentDevice.Port == 0)
                {
                    int.TryParse(TBox_Port.Text, out int port);
                    App.CurrentDevice.Port = port;
                }
                // socket tcp
                if (App.CurrentDevice.IsServer)
                {
                    // server
                    App.Comm = new SocketTcpServerCommunication(App.CurrentDevice.Ip, App.CurrentDevice.Port);
                    ViewModelHelper.SetComm(App.Comm);
                    Panel_ClientsIp.Visibility = Visibility.Visible;
                }
                else
                {
                    // client
                    App.Comm = new SocketTcpClientCommunication(App.CurrentDevice.Ip, App.CurrentDevice.Port);
                }
            }

            if (App.Comm.Open())
            {
                ChangeIsEnabled(false);
                Btn_Switch.Content = StaticData.CLOSE;
                TbBlock_CommunicationStatus.Text = StaticData.OPEN;
            }
            else
            {
                MessageBox.Show("通讯打开失败");
            }
        }

        private void CloseCommunication()
        {
            if (App.Comm != null)
            {
                App.Comm.IsOpen = false;
            }
            App.Comm?.Close();
            App.Comm?.Dispose();
            App.Comm = null;
            ChangeIsEnabled(true);
            Btn_Switch.Content = StaticData.OPEN;
            TbBlock_CommunicationStatus.Text = StaticData.CLOSE;
            Panel_ClientsIp.Visibility = Visibility.Collapsed;
        }

        private void ChangeIsEnabled(bool value)
        {
            CbBox_SerialPort.IsEnabled = value;
            CbBox_BaudRate.IsEnabled = value;
            CbBox_DataBits.IsEnabled = value;
            CbBox_ParityBits.IsEnabled = value;
            CbBox_StopBits.IsEnabled = value;
            CbBox_CorS.IsEnabled = value;
            CbBox_IpAddress.IsEnabled = value;
            TBox_Port.IsEnabled = value;
        }

        private void Btn_Switch_Click(object sender, RoutedEventArgs e)
        {
            InitializeClientIpPanel();
            if (Tabs_CommModeSetting.Visibility == Visibility.Visible)
            {
                App.CurrentDevice.CommMode = Tabs_CommModeSetting.SelectedIndex == 0 ? StaticData.SERIALPORT : StaticData.SOCKETTCP;
                UpdateCurrentDevice();
            }
            if (App.Comm?.IsOpen==true)
            {
                CloseCommunication();
            }
            else
            {
                try
                {
                    OpenCommunication();
                }catch(Exception ex){
                    MessageBox.Show("通信打开失败，请检查参数设置!");
                }
            }
        }

        private void InitializeClientIpPanel()
        {
            // ClientIP ComboBox default value
            lstClientIp = new ObservableCollection<string>();
            ViewModelHelper.LstClient = lstClientIp;
            int count = lstClientIp.Count;
            lstClientIp.Add($"All Connections({count})");
            ViewModelHelper.CBboxCientsIp = this.CbBox_ClientsIp;
            this.CbBox_ClientsIp.ItemsSource = lstClientIp;//binding
            this.CbBox_ClientsIp.SelectedIndex = 0;
        }

        // 关闭所有通讯 保存用户数据
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            CloseCommunication();

            // 关闭前保存用户使用数据
            database.UpdateNormalDevice(App.CurrentDevice);
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            System.Environment.Exit(0);
        }

        private void ChangedChecked(object sender, RoutedEventArgs e)
        {
            if (IsLoaded)
            {
                ViewModelHelper.SetEncoding(this);
            }
        }

        private void CbBox_ClientsIp_SourceUpdated(object sender, DataTransferEventArgs e)
        {
            ComboBox cbBoxClientsIp = sender as ComboBox;
            if (cbBoxClientsIp != null)
            {
                this.CbBox_ClientsIp.SelectedIndex = 0;
                MessageBox.Show("1");
            }
        }

        private void Tabs_CommModeSetting_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.Source==Tabs_CommModeSetting)
            {
                // 判断触发此事件的控件对象是不是Tabs_CommModeSetting，因为此事件 冒泡
                CloseCommunication();
            }
        }

        private void lBox_Devices_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            CloseCommunication();
        }
    }
}

    
